//
//  UpdateViewController.m
//  XRmenu
//
//  Created by Chow Akins on 11-11-23.
//  Copyright 2011年 foxhis. All rights reserved.
//

#import "UpdateViewController.h"
#define kTagOfStartUpdateText 8156

@interface UpdateViewController()

- (BOOL)menuUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)dishUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)cigaretteUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)setMealUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)drinkUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)seasonDishUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)specCodeUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)productTagUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)createDocumentsFoldersError:(XRmenuError **)error;
- (BOOL)fileUpdate:(NSString *)baseUrl Error:(XRmenuError **)error;
- (BOOL)productRelationShipUpdate:(NSString *)baseUrl;
- (NSArray *)clearFileByRemoteFileList:(NSArray *)remoteFileList;
- (BOOL)clearFolder;
- (BOOL)clearFiles;
- (BOOL)clearGridImages;
@end

@implementation UpdateViewController

@synthesize tableUpdateLabel;
@synthesize firstMessage;
@synthesize exceptionMessage;
@synthesize curIndex;
@synthesize fileCount;
@synthesize progressbar;
@synthesize departmentId;

#pragma mark 多线程处理
-(void)startBackgroundJob
{
	NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
	[self startUpdate];
	[pool release];
}

-(void)handleUpdateProgress:(NSNotification *)notification
{
	DebugLog(@"刷新UI。。。。。");
	[self performSelectorOnMainThread:@selector(UpdateProgress:) withObject:nil waitUntilDone:YES];
}

- (void)UpdateProgress:(id)sender
{
	self.tableUpdateLabel.text = self.firstMessage;
	if (fileCount > curIndex) {
		float steps = (float) curIndex / fileCount;
		self.progressbar.progress = steps;
	}else {
		self.progressbar.progress = 1;
	}
    //增加更新异常信息
    if ([self.exceptionMessage length]>0) {
        UITextView *txtv=(UITextView *)[self.view viewWithTag:kTagOfStartUpdateText];
        [txtv setText:[NSString stringWithFormat:@"%@\r\n%@",txtv.text, self.exceptionMessage]];
        [txtv scrollRectToVisible:CGRectMake(0, txtv.contentSize.height-5, txtv.contentSize.width, 10) animated:YES];
        self.exceptionMessage=@"";
    }
}

-(void)notifyMessage
{
	[[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshUI" object:nil];
}

#pragma mark -
#pragma mark 更新模块

- (BOOL)createDocumentsFoldersError:(XRmenuError **)error
{
	BOOL status = YES;
	
	NSString *folder = [NSString stringWithFormat:@"%@/XRmenu",[XRmenuFileManage documentPath]];
	if ([[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:error]) {
		DebugLog(@"Create Folder:%@ Sucess!",folder);
	}else {
		DebugLog(@"Create Folder:%@ Failure!Reason:%@",folder, [*error userInfo]);
		return NO;
	}
	
	NSArray *subFolders = [NSArray arrayWithObjects:@"album",@"audio",@"detail",@"nameimage",@"photo",@"vedio",@"ad",nil];
	
	for (NSString *subFolder in subFolders) {
		NSString *path = [NSString stringWithFormat:@"%@/%@",folder,subFolder];
		if ([[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:error]) {
			DebugLog(@"Create Folder:%@ Sucess!",path);
		}else {
			DebugLog(@"Create Folder:%@ Failure!Reason:%@",path, [*error userInfo]);
			return NO;
		}
	}
	return status;
}

- (BOOL)clearFolder
{
	NSArray *folders = [NSArray arrayWithObjects:@"commend",@"ad/others",nil];
	
	for (NSString *folder in folders) {
		NSString *path = [[XRmenuFileManage documentPath] stringByAppendingPathComponent:folder];
		if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
			[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
		}
	}
	return YES;
}

- (NSArray *)clearFileByRemoteFileList:(NSArray *)remoteFileList
{
	NSArray *localFileList =  [XRmenuFileManage allFilesInPathAndItsSubpaths:[XRmenuFileManage documentPath]];
	NSMutableArray *newRemoteFileList = [remoteFileList mutableCopy];
	
	int totalFileCount = [localFileList count];
	int i = 0;
	self.firstMessage = @"开始检测无效文件!";
	[self notifyMessage];
	
	for (NSString *localPath in localFileList) {//遍历ipad上的图片路径
		// 确保为需要的文件夹
		if ([localPath isContainsString:@"XRmenu/"]) {
			BOOL isFind = NO;
			NSMutableIndexSet *noNeedRemoteFileIS = [[NSMutableIndexSet alloc] init];
			for (int i = 0; i < [newRemoteFileList count]; i++) {
				IDocFile *docFile = [newRemoteFileList objectAtIndex:i];
				NSString *docFileName = [docFile.fileName stringByReplacingOccurrencesOfString:@"product" withString:@"XRmenu"];
				docFileName = [docFileName stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
				
				if ([localPath isEqualToString:docFileName]) {
					localPath = [[XRmenuFileManage documentPath] stringByAppendingPathComponent:localPath];
					if ([XRmenuFileManage fileAttributes:localPath	targetSize:docFile.fileSize]) {
						DebugLog(@"%@文件大小相同无需更新!", localPath);
						[newRemoteFileList removeObjectAtIndex:i]; //从数组中移除
					}else {
						[XRmenuFileManage fileDelete:localPath];
					}
					isFind = YES;
					break; //跳出当前循环 
				}
			}
			if (!isFind) {
				[XRmenuFileManage fileDelete:[[XRmenuFileManage documentPath] stringByAppendingPathComponent:localPath]];
			}
			[newRemoteFileList removeObjectsAtIndexes:noNeedRemoteFileIS];
			[noNeedRemoteFileIS release];
		}
		
		i++;
		self.firstMessage = [NSString stringWithFormat:@"正在检测无效文件:(%d/%d)",i,totalFileCount];
		[self notifyMessage];
	}
	return [newRemoteFileList autorelease];
}

- (BOOL)clearFiles
{
	int totalFiels=0;
	int i =0 ;
	
	NSArray *materialFiles = [XRmenuFileManage allFilesInPathAndItsSubpaths:[[XRmenuFileManage documentPath] stringByAppendingPathComponent:@"XRmenu/dishphoto"]];
	totalFiels += [materialFiles count];
	self.firstMessage = @"开始删除图片文件！";
	[self notifyMessage];
	
	//处理XRmenu文件 全部删除
	for (NSString *materialFile in materialFiles) {
        DebugLog(@"deleteFile=%@", materialFile);
        [XRmenuFileManage fileDelete:[[XRmenuFileManage documentPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"XRmenu/dishphoto/%@",materialFile]]];
        i++;
		self.firstMessage = [NSString stringWithFormat:@"正在删除图片文件:(%d/%d)",i,totalFiels];
		[self notifyMessage];
	}
	return YES;
}

- (BOOL)clearGridImages
{
	int totalFiels=0;
	int i =0 ;
	
	NSArray *materialFiles = [XRmenuFileManage allFilesInPathAndItsSubpaths:[[XRmenuFileManage documentPath] stringByAppendingPathComponent:@"XRmenu/grid"]];
	totalFiels += [materialFiles count];
	self.firstMessage = @"开始删除缩略图片文件！";
	[self notifyMessage];
	
	//处理XRmenu文件 全部删除
	for (NSString *materialFile in materialFiles) {
        DebugLog(@"deleteFile=%@", materialFile);
        [XRmenuFileManage fileDelete:[[XRmenuFileManage documentPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"XRmenu/grid/%@",materialFile]]];
        i++;
		self.firstMessage = [NSString stringWithFormat:@"正在删除缩略图片文件:(%d/%d)",i,totalFiels];
		[self notifyMessage];
	}
	return YES;
}

- (BOOL)fileUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSArray *fileList = [XRmenuHelper docFilesAll:baseUrl Error:error];
	fileList = [self clearFileByRemoteFileList:fileList];
	if (!*error) {		
		int docFileCount = [fileList count];
		int i = 0;
		for (IDocFile *file in fileList) {
			NSString *localName = [file.fileName stringByReplacingOccurrencesOfString:@"product" withString:@"XRmenu"];
			localName = [localName stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
			
			//处理(推荐页/ad)
			NSArray *paths = [localName componentsSeparatedByString:@"/"];
			NSString *departmentStr = [[[self departmentId] stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
			
			if ([paths count] > 1) {
				if ([arrayObject(paths,0) isEqualToString:@"commend"] || [arrayObject(paths,0) isEqualToString:@"ad"]) {
					if ([arrayObject(paths,1) isEqualToString:departmentStr]) {
						
						localName = [localName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"/%@/",departmentStr]
																		 withString:@"/"];
					}else {
						continue;
					}
                    
				}
			}
            
            
			localName = [NSString stringWithFormat:@"%@/%@",[XRmenuFileManage documentPath],localName];
			
			if ([XRmenuFileManage fileExistByPath:localName]) {
				
				if ([XRmenuFileManage fileAttributes:localName targetSize:file.fileSize]) {
					DebugLog(@"%@文件大小相同无需更新!", localName);
				}else {
					[XRmenuHelper downloadFile:file.downloadUrl LocalFolder:localName];
					DebugLog(@"下载文件路径:%@",file.downloadUrl);
				}
				
			}else {
				
				NSArray *folders = [localName componentsSeparatedByString:@"/"];
				NSString *finalFolder = @"/";
				for (int i = 0; i < [folders count] - 1; i++) {
					finalFolder = [finalFolder stringByAppendingPathComponent:[folders objectAtIndex:i]];
				}
				
				NSError *error = nil;
				BOOL isDir;
				BOOL temp = [[NSFileManager defaultManager] fileExistsAtPath:finalFolder isDirectory:&isDir];
                
				if (!temp) {
					if ([[NSFileManager defaultManager] createDirectoryAtPath:finalFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
						DebugLog(@"%@文件夹创建成功!",finalFolder);
					}else {
						DebugLog(@"%@文件夹创建失败:%@",finalFolder, [error userInfo]);
						return NO;
					}
				}
				
				[XRmenuHelper downloadFile:file.downloadUrl LocalFolder:localName];
				DebugLog(@"下载文件路径:%@",file.downloadUrl);
			}
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新菜谱图片数据:(%d/%d)",i,docFileCount];
			[self notifyMessage];
		}
		
	}else {
		DebugLog(@"更新文件错误:%@", [*error userInfo]);
		return NO;
	} 
    
	return YES;
}

- (BOOL)dishUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	DebugLog(@"%@", @"-------dishUpdate 开始-------");
	
	NSArray *iDishes = [XRmenuHelper dishesAll:baseUrl DepartmentId:self.departmentId Error:error];//[XRmenuHelper dishesAll:baseUrl Error:error];
	int dishCount = [iDishes count];
	int i = 0;
	if (!*error) {
		
		for (IDish *iDish in iDishes) {
			
			Dish *dish = [NSEntityDescription insertNewObjectForEntityForName:@"Dish" inManagedObjectContext:MOC];
			
			[dish setDDishId:iDish.dishId];
			[dish setDID:num(iDish.Id)];
			[dish setDSpellCode:iDish.spellCode];
			
			if (iDish.dishLanguaegExs) {
				
				for (IDishLanguageEx *iDishLanguageEx in iDish.dishLanguaegExs) {
					DishLanguageEx *dishLangaugeEx = [NSEntityDescription insertNewObjectForEntityForName:@"DishLanguageEx" inManagedObjectContext:MOC];
					[dishLangaugeEx setDBriefEx:nullstr(iDishLanguageEx.briefEx)];
					[dishLangaugeEx setDCommentEx:nullstr(iDishLanguageEx.commentEx)];
					[dishLangaugeEx setDLanguage:iDishLanguageEx.language];
					[dishLangaugeEx setDMaterialEx:nullstr(iDishLanguageEx.materialEx)];
					[dishLangaugeEx setDNameEx:iDishLanguageEx.nameEx];
					[dishLangaugeEx setDRecipesEx:nullstr(iDishLanguageEx.recipesEx)];
					[dishLangaugeEx setDUnit:nullstr(iDishLanguageEx.unit)];
					
					DebugLog(@"当前菜语言扩展名称:%@", dishLangaugeEx.dNameEx);
					[dishLangaugeEx setRsToDish:dish];
				}
				
			}else {
				DebugLog(@"%@", @"没有菜语言扩展内容！");
				NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:@"没有菜语言扩展内容！",NSLocalizedDescriptionKey,nil];
				*error = [XRmenuError errorWithDomain:@"XRmenu1.0" code:-10001 userInfo:userInfo];
				[userInfo release];
				return NO;
			}
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新菜肴数据:(%d/%d)",i,dishCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			DebugLog(@"%@", @"-------dishUpdate 成功-------");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
			return NO;
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
		return NO;
	}
	DebugLog(@"%@", @"-------dishUpdate 结束-------");
	return YES;
}

- (BOOL)cigaretteUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------cigaretteUpdate 开始-------");
	NSArray *iCigarettes = [XRmenuHelper cigarettesAll:baseUrl DepartmentId:self.departmentId Error:error];
	int cigaretteCount = [iCigarettes count];
	int i = 0;
	if (!*error) {
		
		for (ICigarette *iCigarette in iCigarettes) {
			Cigarette *cig = [NSEntityDescription insertNewObjectForEntityForName:@"Cigarette" inManagedObjectContext:MOC];
			[cig setCCigaretteId:iCigarette.cigaretteId];
			[cig setCCO:iCigarette.CO];
			[cig setCID:num(iCigarette.Id)];
			[cig setCName:iCigarette.name];
			[cig setCNicotine:iCigarette.nicotine];
			[cig setCPackage:iCigarette.package];
			[cig setCSpecification:iCigarette.specification];
			[cig setCTar:iCigarette.tar];
			[cig setCSpellCode:iCigarette.spellCode];
			
			DebugLog(@"当前香烟的名称:%@", cig.cName);
			
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新香烟数据:(%d/%d)",i,cigaretteCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"cigaretteUpdate 成功!");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------cigaretteUpdate 结束-------");
	
	return status;
}

- (BOOL)setMealUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------setMealUpdate 开始-------");
	NSArray *iSetMeals = [XRmenuHelper setMealsAll:baseUrl DepartmentId:self.departmentId Error:error];
	int setMealCount = [iSetMeals count];
	int i = 0;
	if (!*error) {
		
		for (ISetMeal *iSetMeal in iSetMeals) {
			SetMeal *setMeal = [NSEntityDescription insertNewObjectForEntityForName:@"SetMeal" inManagedObjectContext:MOC];
			[setMeal setSName:iSetMeal.name];
			[setMeal setSSetMealId:iSetMeal.setMealId];
			[setMeal setSSummary:nullstr(iSetMeal.summary)];
			[setMeal setSSpellCode:iSetMeal.spellCode];
			
			DebugLog(@"当前套餐名称:%@", setMeal.sName);
			
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新套餐数据:(%d/%d)",i,setMealCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"setMealUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------setMealUpdate 结束-------");
	return status;
}

- (BOOL)drinkUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------drinkUpdate 开始-------");
	NSArray *iDrinks = [XRmenuHelper drinksAll:baseUrl DepartmentId:self.departmentId Error:error];
	int drinkCount = [iDrinks count];
	int i = 0;
	if (!*error) {
		for (IDrink *iDrink in iDrinks) {
			Drink *drink = [NSEntityDescription insertNewObjectForEntityForName:@"Drink" inManagedObjectContext:MOC];
			[drink setDCapacity:nullstr(iDrink.capacity)];
			[drink setDDrinkId:iDrink.drinkId];
			[drink setDID:num(iDrink.Id)];
			[drink setDName:iDrink.name];
			[drink setDPlace:iDrink.place];
			[drink setDPrecision:iDrink.precision];
			[drink setDTemperature:iDrink.temperature];
			[drink setDYear:iDrink.year];
			[drink setDSpellCode:iDrink.spellCode];
			
			DebugLog(@"当前酒水名称:%@", drink.dName);
			
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新酒水数据:(%d/%d)",i,drinkCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"drinkUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------drinkUpdate 结束-------");
	return status;
}

- (BOOL)seasonDishUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------seasonDishUpdate 开始-------");
	NSArray *iSeasonDishes = [XRmenuHelper seasonDishesAll:baseUrl DepartmentId:self.departmentId Error:error];
	int seasonDishCount = [iSeasonDishes count];
	int i = 0;
	if (!*error) {
		
		for (ISeasonDish *iSeasonDish in iSeasonDishes) {
			SeasonDish *sd = [NSEntityDescription insertNewObjectForEntityForName:@"SeasonDish" inManagedObjectContext:MOC];
			[sd setSCookeryOptions:nullstr(iSeasonDish.cookeryOptions)];
			[sd setSID:num(iSeasonDish.Id)];
			[sd setSName:iSeasonDish.name];
			[sd setSSeasonDishId:iSeasonDish.seasonDishId];
			[sd setSSpellCode:iSeasonDish.spellCode];
			
			DebugLog(@"当前时价菜名称:%@", sd.sName);
			
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新时价菜数据:(%d/%d)",i,seasonDishCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"seasonDishUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------seasonDishUpdate 结束-------");
	return status;
}

- (BOOL)specCodeUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------specCodeUpdate 开始-------");
	NSArray *iSpecCodes = [XRmenuHelper specCodesAll:baseUrl DepartmentId:self.departmentId Error:error];
	int specCodeCount = [iSpecCodes count];
	int i = 0;
	if (!*error) {
		
		for (ISpecCode *iSpecCode in iSpecCodes) {
			SpecCode *specCode = [NSEntityDescription insertNewObjectForEntityForName:@"SpecCode" inManagedObjectContext:MOC];
			[specCode setSCheckInTime:iSpecCode.checkInTime];
			[specCode setSCode:iSpecCode.code];
			[specCode setSID:num(iSpecCode.Id)];
			[specCode setSName:iSpecCode.name];
			[specCode setSSpecCodeId:iSpecCode.specCodeId];
			[specCode setSStatus:num(iSpecCode.status)];
			//[specCode setSType:num(iSpecCode.type)];
            
			DebugLog(@"当前改码名称:%@", specCode.sName);
			
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新改码数据:(%d/%d)",i,specCodeCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"specCodeUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
			
			NSArray* detailedErrors = [[*error userInfo] objectForKey:NSDetailedErrorsKey];
			if(detailedErrors != nil && [detailedErrors count] > 0) {
				for(NSError* detailedError in detailedErrors) {
					DebugLog(@"  DetailedError: %@", [detailedError userInfo]);
				}
			}
			else {
				DebugLog(@"  %@", [*error userInfo]);
			}
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------specCodeUpdate 结束-------");
	return status;
}

- (BOOL)productTagUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------productTagUpdate 开始-------");
	NSArray *iProductTags = [XRmenuHelper productTagsAll:baseUrl DepartmentId:self.departmentId Error:error];
	int productTagCount = [iProductTags count];
	int i = 0;
	if (!*error) {
		
		for (IProductTag *iProductTag in iProductTags) {
			ProductTag *productTag = [NSEntityDescription insertNewObjectForEntityForName:@"ProductTag" inManagedObjectContext:MOC];
			[productTag setTCheckInTime:iProductTag.checkInTime];
			[productTag setTID:num(iProductTag.Id)];
			[productTag setTKeyword:iProductTag.keyword];
			[productTag setTLanguageEx:iProductTag.languageEx];
			[productTag setTProductNum:num(iProductTag.productNum)];
			[productTag setTStatus:num(iProductTag.status)];
			[productTag setTTagId:iProductTag.tagId];
			
			DebugLog(@"当前标签关键字为：%@", productTag.tKeyword);
			i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新标签数据:(%d/%d)",i,productTagCount];
			[self notifyMessage];
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"productTagUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------productTagUpdate 结束-------");
	return status;
}

- (BOOL)menuUpdate:(NSString *)baseUrl Error:(XRmenuError **)error
{
	
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	BOOL status = NO;
	
	DebugLog(@"%@", @"-------menuUpdate 开始-------");
	NSArray *iMenus = [XRmenuHelper menuBooksAll:baseUrl DepartmentId:self.departmentId Error:error];
	
	if (!*error) {
		APPSESSION.currentBookID = [iMenus count] > 0 ? arrayObject(iMenus,0) : nil;
		int menuCount = [iMenus count];
		int i = 0;
		for (IMenu *iMenu in iMenus) {
			i++;
			Menu *menu = [NSEntityDescription insertNewObjectForEntityForName:@"Menu" inManagedObjectContext:MOC];
			[menu setValue:iMenu.checkInTime forKey:@"mCheckInTime"];
			[menu setValue:num(iMenu.departmentId) forKey:@"mDepartmentID"];
			[menu setValue:num(i) forKey:@"mID"];
			[menu setValue:iMenu.menuId forKey:@"mMenuId"];
			[menu setValue:num(iMenu.productsCount) forKey:@"mProductsCount"];
			[menu setValue:num(iMenu.status) forKey:@"mStatus"];
			[menu setValue:iMenu.name forKey:@"mName"];
			
			DebugLog(@"当前菜本名称为: %@", iMenu.name);
			
			DebugLog(@"开始更新菜本---%@---下的分类", iMenu.name);
			NSArray *iCatalogs = [XRmenuHelper catalogsAll:baseUrl menuId:iMenu.menuId Error:error];
			int catalogCount = [iCatalogs count];
			int ii = 0; int ci = 0; int pi = 0;
			if (!*error) {
				
				for (ICatalogs *iCatalog in iCatalogs) {
					ii++; ci++;
					Catalogs *catalog = [NSEntityDescription insertNewObjectForEntityForName:@"Catalogs" inManagedObjectContext:MOC];
					[catalog setValue:iCatalog.catalogsId forKey:@"cCatalogsId"];
					[catalog setValue:num(iCatalog.type) forKey:@"cCatalogsType"];
					[catalog setValue:iCatalog.checkInTime forKey:@"cCheckInTime"];
					[catalog setValue:nullstr(iCatalog.comment) forKey:@"cComment"];
					[catalog setValue:num(iCatalog.depth) forKey:@"cDepth"];
					[catalog setValue:num(iCatalog.dishCount) forKey:@"cDishCount"];
					[catalog setValue:iCatalog.globalPath forKey:@"cGlobalPath"];
					[catalog setValue:num(ci) forKey:@"cID"];
					[catalog setValue:iCatalog.name forKey:@"cName"];
					[catalog setValue:num(iCatalog.orderNo) forKey:@"cOrderNo"];
					[catalog setValue:iCatalog.parentId forKey:@"cParentId"];
					[catalog setValue:num(iCatalog.status) forKey:@"cStatus"];
					
                    [menu addRsToCatalogsObject:catalog];
					DebugLog(@"当前菜类名称为: %@---菜类编号:%@", iCatalog.name,iCatalog.catalogsId);
					
                    
					NSArray *iProducts = [XRmenuHelper productAll:baseUrl catalogsId:iCatalog.catalogsId Error:error];
					
					if (!*error) {
						int productCount = [iProducts count];
						int iii = 0; 
						DebugLog(@"-----开始更新%@下面的商品", iCatalog.name);
						for (IProduct *iProduct in iProducts) {
							iii++; pi++;
							Product *product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:MOC];
							[product setValue:num(iProduct.color) forKey:@"pColor"];
							[product setValue:num(iProduct.commentNum) forKey:@"pCommentNum"];
							[product setValue:iProduct.entityId forKey:@"pEntityId"];
							[product setValue:num(pi) forKey:@"pID"];
							[product setValue:num(iProduct.isRecommend) forKey:@"pIsRecommend"];
							[product setValue:iProduct.position forKey:@"pPosition"];
							[product setValue:iProduct.productId forKey:@"pProductId"];
							[product setValue:iProduct.productNo forKey:@"pProductNo"];
							[product setValue:iProduct.salePrice forKey:@"pSalePrice"];
							[product setValue:iProduct.scoreCount forKey:@"pScoreCount"];
							[product setValue:num(iProduct.status) forKey:@"pStatus"];
							[product setValue:num(iProduct.type) forKey:@"pType"];
							[product setValue:iProduct.unit forKey:@"pUnit"];
							[product setValue:iProduct.capacity forKey:@"pCapacity"];
							[product setValue:iProduct.checkInTime forKey:@"pCheckInTime"];
							//[product setValue:iProduct.spellCode forKey:@"pSpellCode"];
							
							DebugLog(@"当前更新商品编号为%@", product.pProductId);
							[catalog addRsToProductObject:product];
							
							
							NSPredicate *predicate=nil;
							switch ([product.pType intValue]) {
								case ProductTypeDish:
									DebugLog(@"%@", @"开始和dish进行关联");
									predicate = [NSPredicate predicateWithFormat:@"dDishId == %@", product.pEntityId];
									NSArray *dishes = [XRmenuCoreData searchObjectsMOC:@"Dish" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									for (Dish *dish in dishes) {
										[product setValue:dish forKey:@"rsToDish"];
										
										NSMutableString *productName = [NSMutableString stringWithString:@""];
										[productName appendString:@"{"];
										for (DishLanguageEx *language in dish.rsToLanguage) {
											[productName appendFormat:@"\"%@\":\"%@\",",language.dLanguage,language.dNameEx];
										}
										NSRange range = {[productName length]-1,1};
										[productName replaceCharactersInRange:range withString:@""];
										[productName appendString:@"}"];
										[product setValue:productName forKey:@"pName"];
										[product setValue:dish.dSpellCode forKey:@"pSpellCode"];
									}
									
									break;
								case ProductTypeSeasonDsih:
									DebugLog(@"%@", @"开始和时价菜关联");
									predicate = [NSPredicate predicateWithFormat:@"sSeasonDishId == %@", product.pEntityId];
									NSArray *seasonDsishes = [XRmenuCoreData searchObjectsMOC:@"SeasonDish" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									for (SeasonDish *sd in seasonDsishes) {
										[product setValue:sd forKey:@"rsToSeasonDish"];
										NSString *name = sd.sName;
										[product setValue:name forKey:@"pName"];
										[product setValue:sd.sSpellCode forKey:@"pSpellCode"];
									}
									break;
								case ProductTypeDrink:
									DebugLog(@"%@", @"开始和Drink进行关联");
									predicate = [NSPredicate predicateWithFormat:@"dDrinkId == %@", product.pEntityId];
									NSArray *drinks = [XRmenuCoreData searchObjectsMOC:@"Drink" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									for (Drink *drink in drinks) {
										[product setValue:drink forKey:@"rsToDrink"];
										NSString *name = drink.dName;
										[product setValue:name forKey:@"pName"];
										[product setValue:drink.dSpellCode forKey:@"pSpellCode"];
									}
									break;
								case ProductTypeCigarette:
									DebugLog(@"%@", @"开始和香烟进行关联");
									predicate = [NSPredicate predicateWithFormat:@"cCigaretteId == %@", product.pEntityId];
									NSArray *cigaretteds = [XRmenuCoreData searchObjectsMOC:@"Cigarette" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									for (Cigarette *cg in cigaretteds) {
										[product setValue:cg forKey:@"rsToCigarette"];
										NSString *name = cg.cName;
										[product setValue:name forKey:@"pName"];
										[product setValue:cg.cSpellCode forKey:@"pSpellCode"];
									}
									break;
								case ProductTypeSetMeal:
									DebugLog(@"%@", @"开始和套餐进行关联");
									predicate = [NSPredicate predicateWithFormat:@"sSetMealId == %@", product.pEntityId];
									NSArray *setMeals = [XRmenuCoreData searchObjectsMOC:@"SetMeal" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									for (SetMeal *setMeal in setMeals) {
										[product setValue:setMeal forKey:@"rsToSetMeal"];
										NSString *name = setMeal.sName;
										[product setValue:name forKey:@"pName"];
										[product setValue:setMeal.sSpellCode forKey:@"pSpellCode"];
									}
									break;
								default:
									break;
							}
							
							
							DebugLog(@"%@", @"开始和套餐进行继续关联");
							
							NSArray *aSetMels = [XRmenuHelper setMeals:baseUrl byProductId:product.pProductId Error:error];
							if (!*error) {
								
								for (ISetMeal *iSetMeal in aSetMels) {
									NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sSetMealId == %@", iSetMeal.setMealId];
									NSArray *setMeals = [XRmenuCoreData searchObjectsMOC:@"SetMeal" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									if ([setMeals count] > 0) {
										SetMeal *set = [setMeals objectAtIndex:0];
										[product setValue:set forKey:@"rsToSetMeal"];
									}
								}
								
							}else {
								DebugLog(@"取----%@----下面的套餐出错误:%@", product.pName, [*error localizedDescription]);
								return NO;
							}
							
							DebugLog(@"%@", @"开始和标签进行继续关联");
							NSArray *iProductTags = [XRmenuHelper productTags:baseUrl byProductId:product.pProductId Error:error];
							if (!*error) {
								
								for (IProductTag *iProductTag in iProductTags) {
									NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tTagId == %@", iProductTag.tagId];
									NSArray *productTags = [XRmenuCoreData searchObjectsMOC:@"ProductTag" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									ProductTag *productTag = [productTags count] > 0 ? [productTags objectAtIndex:0] : nil;
									[product addRsToProductTagObject:productTag];
								}
								
							}else {
								DebugLog(@"取----%@----下面的标签出错误:%@", product.pName, [*error localizedDescription]);
								return NO;
							}
							
							DebugLog(@"%@", @"开始和改码进行继续关联");
							NSArray *iSpecCodes = [XRmenuHelper specCodes:baseUrl byProductId:product.pProductId Error:error];
							if (!*error) {
								
								for (ISpecCode *iSpecCode in iSpecCodes) {
									NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sSpecCodeId == %@", iSpecCode.specCodeId];
									NSArray *specCodes = [XRmenuCoreData searchObjectsMOC:@"SpecCode" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
									
									SpecCode *specCode = [specCodes count] > 0 ? [specCodes objectAtIndex:0] : nil;
									[product addRsToSpecCodeObject:specCode];
								}
								
							}else {
								DebugLog(@"取----%@----下面的改码出错误:%@", product.pName, [*error localizedDescription]);
								return NO;
							}
							
							//iii++;
							self.firstMessage = [NSString stringWithFormat:@"正在更新%@下的商品:(%d/%d)",JsonFiled(catalog.cName),iii,productCount];
							[self notifyMessage];
							status = YES;
						}
						
					}else {
						DebugLog(@"取----%@----下面的商品出错:%@", iCatalog.name, [*error localizedDescription]);
						return status;
					}
					
					//ii++;
					self.firstMessage = [NSString stringWithFormat:@"正在更新%@下的分类:(%d/%d)",JsonFiled(menu.mName),ii,catalogCount];
					[self notifyMessage];
				}
				
			}else {
				DebugLog(@"更新菜本%@下的分类发生错误:%@",menu.mName, [*error localizedDescription]);
				return status;
			}
			
			//i++;
			self.firstMessage = [NSString stringWithFormat:@"正在更新菜本数据:(%d/%d)",i,menuCount];
			[self notifyMessage];
            
		}
		
		if ([MOC save:error]) {
			status = YES;
			DebugLog(@"%@", @"menuUpdate 更新成功");
		}else {
			DebugLog(@"Unresolved Error:%@", [*error localizedDescription]);
		}
		
	}else {
		DebugLog(@"%@", [*error localizedDescription]);
	}
	DebugLog(@"%@", @"-------menuUpdate 结束-------");
	//temp
	APPSESSION.currentBookID = @"c381137d-3369-42ed-b4b3-498fe5191d6e";
	return status;
}

- (BOOL)productRelationShipUpdate:(NSString *)baseUrl
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
	NSArray *products = [XRmenuCoreData searchObjectsMOC:@"Product" Predicate:nil SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
	XRmenuError *error = nil;
	for (Product *product in products) {
		
		NSPredicate *predicate=nil;
		switch ([product.pType intValue]) {
			case ProductTypeDish:
				DebugLog(@"%@", @"开始和dish进行关联");
				predicate = [NSPredicate predicateWithFormat:@"dDishId == %@", product.pEntityId];
				NSArray *dishes = [XRmenuCoreData searchObjectsMOC:@"Dish" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				for (Dish *dish in dishes) {
					[product setValue:dish forKey:@"rsToDish"];
					
					NSMutableString *productName = [NSMutableString stringWithString:@""];
					[productName appendString:@"{"];
					for (DishLanguageEx *language in dish.rsToLanguage) {
						[productName appendFormat:@"\"%@\":\"%@\",",language.dLanguage,language.dNameEx];
					}
					NSRange range = {[productName length]-1,1};
					[productName replaceCharactersInRange:range withString:@""];
					[productName appendString:@"}"];
					[product setValue:productName forKey:@"pName"];
				}
                
				break;
			case ProductTypeSeasonDsih:
				DebugLog(@"%@", @"开始和时价菜关联");
				predicate = [NSPredicate predicateWithFormat:@"sSeasonDishId == %@", product.pEntityId];
				NSArray *seasonDsishes = [XRmenuCoreData searchObjectsMOC:@"SeasonDish" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				for (SeasonDish *sd in seasonDsishes) {
					[product setValue:sd forKey:@"rsToSeasonDish"];
					NSString *name = sd.sName;
					[product setValue:name forKey:@"pName"];
				}
				break;
			case ProductTypeDrink:
				DebugLog(@"%@", @"开始和Drink进行关联");
				predicate = [NSPredicate predicateWithFormat:@"dDrinkId == %@", product.pEntityId];
				NSArray *drinks = [XRmenuCoreData searchObjectsMOC:@"Drink" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				for (Drink *drink in drinks) {
					[product setValue:drink forKey:@"rsToDrink"];
					NSString *name = drink.dName;
					[product setValue:name forKey:@"pName"];
				}
				break;
			case ProductTypeCigarette:
				DebugLog(@"%@", @"开始和香烟进行关联");
				predicate = [NSPredicate predicateWithFormat:@"cCigaretteId == %@", product.pEntityId];
				NSArray *cigaretteds = [XRmenuCoreData searchObjectsMOC:@"Cigarette" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				for (Cigarette *cg in cigaretteds) {
					[product setValue:cg forKey:@"rsToCigarette"];
					NSString *name = cg.cName;
					[product setValue:name forKey:@"pName"];
				}
				break;
			case ProductTypeSetMeal:
				DebugLog(@"%@", @"开始和套餐进行关联");
				predicate = [NSPredicate predicateWithFormat:@"sSetMealId == %@", product.pEntityId];
				NSArray *setMeals = [XRmenuCoreData searchObjectsMOC:@"SetMeal" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				for (SetMeal *setMeal in setMeals) {
					[product setValue:setMeal forKey:@"rsToSetMeal"];
					NSString *name = setMeal.sName;
					[product setValue:name forKey:@"pName"];
				}
				break;
			default:
				break;
		}
		
		
		DebugLog(@"%@", @"开始和套餐进行继续关联");
		
		NSArray *aSetMels = [XRmenuHelper setMeals:baseUrl byProductId:product.pProductId Error:&error];
		if (!error) {
			
			for (ISetMeal *iSetMeal in aSetMels) {
				NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sSetMealId == %@", iSetMeal.setMealId];
				NSArray *setMeals = [XRmenuCoreData searchObjectsMOC:@"SetMeal" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				if ([setMeals count] > 0) {
					SetMeal *set = [setMeals objectAtIndex:0];
					[product setValue:set forKey:@"rsToSetMeal"];
				}
			}
			
		}else {
			DebugLog(@"取----%@----下面的套餐出错误:%@", product.pName, [error localizedDescription]);
			return NO;
		}
		
		DebugLog(@"%@", @"开始和标签进行继续关联");
		NSArray *iProductTags = [XRmenuHelper productTags:baseUrl byProductId:product.pProductId Error:&error];
		if (!error) {
			
			for (IProductTag *iProductTag in iProductTags) {
				NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tTagId == %@", iProductTag.tagId];
				NSArray *productTags = [XRmenuCoreData searchObjectsMOC:@"ProductTag" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				ProductTag *productTag = [productTags count] > 0 ? [productTags objectAtIndex:0] : nil;
				[product addRsToProductTagObject:productTag];
			}
			
		}else {
			DebugLog(@"取----%@----下面的标签出错误:%@", product.pName, [error localizedDescription]);
			return NO;
		}
		
		DebugLog(@"%@", @"开始和改码进行继续关联");
		NSArray *iSpecCodes = [XRmenuHelper specCodes:baseUrl byProductId:product.pProductId Error:&error];
		if (!error) {
			
			for (ISpecCode *iSpecCode in iSpecCodes) {
				NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sSpecCodeId == %@", iSpecCode.specCodeId];
				NSArray *specCodes = [XRmenuCoreData searchObjectsMOC:@"SpecCode" Predicate:predicate SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
				
				SpecCode *specCode = [specCodes count] > 0 ? [specCodes objectAtIndex:0] : nil;
				[product addRsToSpecCodeObject:specCode];
			}
			
		}else {
			DebugLog(@"取----%@----下面的改码出错误:%@", product.pName, [error localizedDescription]);
			return NO;
		}
		
	}
	
	if ([MOC save:&error]) {
		
		DebugLog(@"%@", @"menuUpdate 更新成功");
	}else {
		DebugLog(@"Unresolved Error:%@", [error localizedDescription]);
		return NO;
	}
	return YES;
}

-(void) startUpdate{
	NSString *baseUrl = [[NSUserDefaults standardUserDefaults] stringForKey:@"download_url"];

	//更新数据
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"update_switch"]) {
		XRmenuError *error = nil;
        NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
		if (![XRmenuHelper reportToCMS:baseUrl UDID:APPSESSION.udid]) {//提交UUID
			DebugLog(@"向CMS报告信息错误!AB1BACC3-C161-570E-9751-7F940AF5DCC9");
		}
		
		if ([XRmenuCoreData clearDBManagedObjectContext:MOC]) {
			self.fileCount = 5;
            
			self.firstMessage = @"开始更新......";
            self.exceptionMessage = @"开始更新......";
			[self notifyMessage];
            
            if (![self XRmenuTablesUpdate:baseUrl Error:&error]) {
				self.exceptionMessage = [NSString stringWithFormat:@"桌号数据下载出错:%@",[error localizedDescription]];
				[self notifyMessage];
				return;
			}
			self.curIndex += 1;
			[self notifyMessage];
            
            if (![self XRmenuSpecialSortUpdate:baseUrl Error:&error]) {
				self.exceptionMessage = [NSString stringWithFormat:@"烧法数据下载出错:%@",[error localizedDescription]];
				[self notifyMessage];
				return;
			}
			self.curIndex += 1;
			[self notifyMessage];
            
			if (![self XRmenuDataBaseUpdate:baseUrl Error:&error]) {
				self.exceptionMessage = [NSString stringWithFormat:@"菜谱信息下载出错:%@",[error localizedDescription]];
				[self notifyMessage];
				return;
			}
			self.curIndex += 1;
			[self notifyMessage];
			
			if (![self XRmenuFilesUpdate:baseUrl Error:&error]) {
				self.exceptionMessage = [NSString stringWithFormat:@"菜品图片下载出错:%@",[error localizedDescription]];
				[self notifyMessage];
				return;
			}
			self.curIndex += 1;
			[self notifyMessage];
            
            if (![self XRmenuOEMPictureUpdate:baseUrl Error:&error]) {
				self.exceptionMessage = [NSString stringWithFormat:@"OEM图片下载出错:%@",[error localizedDescription]];
				[self notifyMessage];
				return;
			}
			self.curIndex += 1;
			[self notifyMessage];
			
			[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"update_switch"];//关闭自动更新设置
            
			//更新完成
			self.firstMessage=@"下载结束!请重启本应用!";
            self.exceptionMessage=@"下载结束!请重启本应用!";
			[self notifyMessage];
		}
	}
}

#pragma mark -
#pragma mark XRmenu菜谱下载
//菜谱下载
-(BOOL) XRmenuDataBaseUpdate:(NSString *)baseUrl Error:(XRmenuError **)outError{
    self.exceptionMessage = @"开始更新菜谱数据...";
    [self notifyMessage];
    NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
    BOOL status = NO;
    
    DebugLog(@"%@",@"-------开始更新XRmenu DataBase...-------");
    NSString *urlPluMenu = [NSString stringWithFormat:@"%@/update/PluMenu",BaseURL(baseUrl)];
	NSArray *arrayPluMenu = [XRmenuHelper getDataFromInternet:urlPluMenu Error:outError];//获得Json字符串数组
    int menuIndex=0;
    int menuCount=[arrayPluMenu count];
    for (NSDictionary *itemMenu in arrayPluMenu) {
        menuIndex++;
        PluMenu *plumenu = [NSEntityDescription insertNewObjectForEntityForName:@"PluMenu" inManagedObjectContext:MOC];
        [plumenu setPmPluCount:num(dictInt(itemMenu,@"pmPluCount"))];//小类的数量
        [plumenu setPmDescripts:dictObject(itemMenu, @"pmDescripts")];//描述
        [plumenu setPmPccode:dictObject(itemMenu, @"pmPccode")];//营业点编号
        [plumenu setPmPluMenuId:dictObject(itemMenu, @"pmPluMenuId")];//大类默认图片
        [plumenu setPmCode:dictObject(itemMenu, @"pmCode")];//大类代码
        [plumenu setPmStatus:num(dictInt(itemMenu, @"pmStatus"))];//是否启用 0-未启用  1-启用
        
        self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在更新大类[code=%@,name=%@]下的小类...",menuIndex,menuCount,plumenu.pmCode,JsonFiled(plumenu.pmDescripts)];
        [self notifyMessage];
        
        NSString *urlPluSort = [NSString stringWithFormat:@"%@/update/PluSort/%@",BaseURL(baseUrl),plumenu.pmCode];
        NSArray *arrayPluSort = [XRmenuHelper getDataFromInternet:urlPluSort Error:outError];//获得Json字符串数组
        int sortIndex=0;
        int sortCount=[arrayPluSort count];
        for (NSDictionary *itemSort in arrayPluSort) {
            sortIndex++;
            PluSort *plusort = [NSEntityDescription insertNewObjectForEntityForName:@"PluSort" inManagedObjectContext:MOC];
            [plusort setPsPluSortId:dictObject(itemSort, @"psPluSortId")];//小类默认图片
            [plusort setPsSortType:dictObject(itemSort, @"psSortType")];//0-食品 1-香烟 2-酒水
            [plusort setPsSort:dictObject(itemSort, @"psSort")];//菜类代码
            [plusort setPsCode:dictObject(itemSort, @"psCode")];//大类代码
            [plusort setPsSpecialSort:dictObject(itemSort, @"psSpecialSort")];//烧法类别代码[001#002#]用于关联烧法类别
            [plusort setPsPluCount:num(dictInt(itemSort, @"psPluCount"))];//该类下的菜品数量
            [plusort setPsDescripts:dictObject(itemSort, @"psDescripts")];//菜类描述
            [plusort setPsSequence:num(dictInt(itemSort, @"psSequence"))];
            [plusort setPsStatus:num(dictInt(itemSort, @"psStatus"))];//是否启用 0-未启用  1-启用
            [plusort setPsRemarks:dictObject(itemSort, @"psRemarks")];
            [plusort setRsToPluMenu:plumenu];//建立小类与大类之间的对应关系(多对一)
            
            self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在更新小类[code=%@,name=%@]下的菜品...",sortIndex,sortCount,plusort.psSort,JsonFiled(plusort.psDescripts)];
            [self notifyMessage];
            
            NSString *urlPluPlu = [NSString stringWithFormat:@"%@/update/PluPlu/%@",BaseURL(baseUrl),plusort.psSort];
            NSArray *arrayPluPlu = [XRmenuHelper getDataFromInternet:urlPluPlu Error:outError];//获得Json字符串数组
            int pluIndex=0;
            int pluCount=[arrayPluPlu count];
            for (NSDictionary *itemPlu in arrayPluPlu) {
                pluIndex++;
                PluPlu *pluplu= [NSEntityDescription insertNewObjectForEntityForName:@"PluPlu" inManagedObjectContext:MOC];
                [pluplu setPpCode:dictObject(itemPlu, @"ppCode")];
                [pluplu setPpColor:dictObject(itemPlu, @"ppColor")];
                [pluplu setPpHelpCode:dictObject(itemPlu, @"ppHelpCode")];
                [pluplu setPpNames:dictObject(itemPlu, @"ppNames")];
                [pluplu setPpPrice:num(dictFloat(itemPlu, @"ppPrice"))];
                [pluplu setPpUnits:dictObject(itemPlu, @"ppUnits")];
                [pluplu setPpPluPluId:dictObject(itemPlu, @"ppPluPluId")];//图片名
                [pluplu setPpPosition:dictObject(itemPlu, @"ppPosition")];
                [pluplu setPpRecommended:num(dictInt(itemPlu, @"ppRecommended"))];//0-普通菜  1-推荐菜
                [pluplu setPpRemarks:dictObject(itemPlu, @"ppRemarks")];
                [pluplu setPpSort:dictObject(itemPlu, @"ppSort")];
                [pluplu setPpStatus:num(dictInt(itemPlu, @"ppStatus"))];//是否启用 0-未启用  1-启用
                [pluplu setPpType:dictObject(itemPlu, @"ppType")];//0-食品 1-香烟 2-酒水
                [plusort addRsToPluPluObject:pluplu];//让菜库和菜类建立对应关系(一对多)
                
                self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在更菜品[code=%@,name=%@]...",pluIndex,pluCount,pluplu.ppCode,JsonFiled(pluplu.ppNames)];
                [self notifyMessage];
                
                if ([pluplu.ppType isEqualToString:@"0"]) {
                    NSString *urlPluFood = [NSString stringWithFormat:@"%@/update/PluFood/%@",BaseURL(baseUrl),pluplu.ppCode];
//                    NSString *temp=@"[{\"pfHelpCode\":\"\",\"pfCapacity\":\"0\",\"pfMeterials\":\"{'zh-Hans':'制作材料','en':'制作材料'}\",\"pfRemarks\":\"{'zh-Hans':'备注 ','en':'备注 '}\",\"pfCooks\":\"{'zh-Hans':'制作方法 ','en':'制作方法 '}\"}]";
                    NSArray *arrayPluFood =[XRmenuHelper getDataFromInternet:urlPluFood Error:outError];//获得Json字符串数组
                    NSDictionary *itemFood=[arrayPluFood objectAtIndex:0];
                    
                    PluFood *plufood= [NSEntityDescription insertNewObjectForEntityForName:@"PluFood" inManagedObjectContext:MOC];
                    [plufood setPfCapacity:num(dictInt(itemFood, @"pfCapacity"))];
                    [plufood setPfCode:dictObject(itemFood, @"pfCode")];//该编号必须和pluplu.ppCode相同
                    [plufood setPfCooks:dictObject(itemFood, @"pfCooks")];
                    [plufood setPfFoodId:dictObject(itemFood, @"pfFoodId")];//图片名2
                    [plufood setPfHelpCode:dictObject(itemFood, @"pfHelpCode")];
                    [plufood setPfMeterials:dictObject(itemFood, @"pfMeterials")];
                    [plufood setPfRemarks:dictObject(itemFood, @"pfRemarks")];
                    [plufood setPfUnitId:num(dictInt(itemFood, @"pfUnitId"))]; 
                    
                    [pluplu setRsToPluFood:plufood];
                }
                else if([pluplu.ppType isEqualToString:@"1"]){
                    NSString *urlPluCigarete = [NSString stringWithFormat:@"%@/update/PluCigarete/%@",BaseURL(baseUrl),pluplu.ppCode];
                    NSArray *arrayPluCigarete = [XRmenuHelper getDataFromInternet:urlPluCigarete Error:outError];//获得Json字符串数组
                    NSDictionary *itemCigarete=[arrayPluCigarete objectAtIndex:0];
                    
                    PluCigarete *plucigarete= [NSEntityDescription insertNewObjectForEntityForName:@"PluCigarete" inManagedObjectContext:MOC];
                    [plucigarete setPcCigareteId:dictObject(itemCigarete, @"pcCigareteId")];//图片名2
                    [plucigarete setPcCO:num(dictInt(itemCigarete, @"pcCO"))];
                    [plucigarete setPcCode:dictObject(itemCigarete, @"pcCode")];
                    [plucigarete setPcHelpCode:dictObject(itemCigarete, @"pcHelpCode")];
                    [plucigarete setPcNicotine:num(dictInt(itemCigarete, @"pcNicotine"))];
                    [plucigarete setPcPackages:dictObject(itemCigarete, @"pcPackages")];
                    [plucigarete setPcRemarks:dictObject(itemCigarete, @"pcRemarks")];
                    [plucigarete setPcTar:num(dictInt(itemCigarete, @"pcTar"))];
                    
                    [pluplu setRsToPluCigarete:plucigarete];
                }
                else if([pluplu.ppType isEqualToString:@"2"]){
                    NSString *urlPluDrink = [NSString stringWithFormat:@"%@/update/PluDrink/%@",BaseURL(baseUrl),pluplu.ppCode];
                    NSArray *arrayPluDrink = [XRmenuHelper getDataFromInternet:urlPluDrink Error:outError];//获得Json字符串数组
                    NSDictionary *itemDrink=[arrayPluDrink objectAtIndex:0];
                    
                    PluDrink *pludrink= [NSEntityDescription insertNewObjectForEntityForName:@"PluDrink" inManagedObjectContext:MOC];
                    [pludrink setPdCapacity:num(dictInt(itemDrink, @"pdCapacity"))];
                    [pludrink setPdCode:dictObject(itemDrink, @"pdCode")];
                    [pludrink setPdDrinkId:dictObject(itemDrink, @"pdDrinkId")];//图片名2
                    [pludrink setPdHelpCode:dictObject(itemDrink, @"pdHelpCode")];
                    [pludrink setPdPlaces:dictObject(itemDrink, @"pdPlaces")];
                    [pludrink setPdPrecision:dictObject(itemDrink, @"pdPrecision")];
                    [pludrink setPdRemarks:dictObject(itemDrink, @"pdRemarks")];
                    [pludrink setPdTempereature:dictObject(itemDrink, @"pdTempereature")];
                    [pludrink setPdYear:dictObject(itemDrink, @"pdYear")];
                    
                    [pluplu setRsToPluDrink:pludrink];
                }
            }
            
            self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在关联小类[code=%@,name=%@]对应的烧法类别...",sortIndex,sortCount,plusort.psSort,JsonFiled(plusort.psDescripts)];
            [self notifyMessage];
            
            DebugLog(@"%@", @"开始和烧法类别进行关联...");
            NSArray *sortCodes = [plusort.psSpecialSort componentsSeparatedByString: @"#"];
            if ([sortCodes count]>0) {
                for (int i=0; i<[sortCodes count]; i++) {
                    NSString *tempSortCode=[sortCodes objectAtIndex:i];
                    if ([tempSortCode length]>0) {
                        DebugLog(@"tempSortCode=%@", tempSortCode);
                        NSString *condition1=[NSString stringWithFormat:@"psSortCode == '%@'",tempSortCode];
                        NSMutableArray *arraySpecialSort1= [XRmenuCoreData searchObjectsInContext:@"PluSpecialSort" 
                                                                                       Predicate:[NSPredicate predicateWithFormat:condition1] 
                                                                                         SortKey:@"psSortCode"
                                                                                   SortAscending:YES];
                        DebugLog(@"count=%d", [arraySpecialSort1 count]);
                        for (PluSpecialSort *specialSort1 in arraySpecialSort1) {                
                            [plusort addRsToPluSpecialSortObject:specialSort1];
                        }
                    }
                }
            }
            
        }
    }
    
    if ([MOC save:outError]) {
        status = YES;
        DebugLog(@"%@", @"XRmenu DataBase 更新成功!");
        self.exceptionMessage=[NSString stringWithFormat:@"菜谱信息 更新成功!"];
        [self notifyMessage];
    }else {
        DebugLog(@"XRmenu DataBase 更新出错:%@", [*outError localizedDescription]);
        self.exceptionMessage=[NSString stringWithFormat:@"菜谱信息 下载出错：%@", [*outError localizedDescription]];
        [self notifyMessage];
    }
    
    DebugLog(@"%@", @"-------XRmenu DataBase 更新结束!-------");
    self.firstMessage = @"菜谱数据更新完毕!";
    [self notifyMessage];
    return status;
}
//桌号下载
-(BOOL) XRmenuTablesUpdate:(NSString *)baseUrl Error:(XRmenuError **)outError{
    self.exceptionMessage = @"开始更新桌号数据...";
    [self notifyMessage];
    NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
    BOOL status = NO;
    DebugLog(@"%@",@"-------开始更新 桌号数据...-------");
    NSString *urlPluTable = [NSString stringWithFormat:@"%@/update/PluTable/%@",BaseURL(baseUrl),APPSESSION.udid];
	NSArray *arrayPluTable = [XRmenuHelper getDataFromInternet:urlPluTable Error:outError];//获得Json字符串数组
    int tableIndex=0;
    int tableCount=[arrayPluTable count];
    for (NSDictionary *itemTable in arrayPluTable) {
        tableIndex++;
        PluTable *plutable = [NSEntityDescription insertNewObjectForEntityForName:@"PluTable" inManagedObjectContext:MOC];
        [plutable setPtTableNo:dictObject(itemTable,@"ptTableNo")];          //桌号编码
        [plutable setPtDescripts:dictObject(itemTable, @"ptDescripts")];     //桌号描述
        
        self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在下载桌号信息...",tableIndex,tableCount];
        [self notifyMessage];
    }
    
    if ([MOC save:outError]) {
        status = YES;
        DebugLog(@"%@", @"桌号数据 更新成功!");
        self.exceptionMessage=[NSString stringWithFormat:@"桌号数据 更新成功!个数：%d",tableIndex];
        [self notifyMessage];
    }else {
        DebugLog(@"桌号数据 更新出错:%@", [*outError localizedDescription]);
        self.exceptionMessage=[NSString stringWithFormat:@"桌号数据更新出错：%@", [*outError localizedDescription]];
        [self notifyMessage];
    }
    
    DebugLog(@"%@", @"-------桌号数据 更新结束!-------");
    self.firstMessage = @"桌号数据更新完毕!";
    [self notifyMessage];
    return status;
}
//烧法下载
-(BOOL) XRmenuSpecialSortUpdate:(NSString *)baseUrl Error:(XRmenuError **)outError{
    self.exceptionMessage = @"开始更新烧法信息...";
    [self notifyMessage];    
    NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] threadManagedObjectContext];
    BOOL status = NO;
    DebugLog(@"%@",@"-------开始更新 烧法...-------");
    
    NSString *urlPluSpecialSort = [NSString stringWithFormat:@"%@/update/PluSpecialSort",BaseURL(baseUrl)];
    NSArray *arrayPluSpecialSort = [XRmenuHelper getDataFromInternet:urlPluSpecialSort Error:outError];//获得Json字符串数组
    int pluSpecialSortIndex=0;
    int pluSpecialSortCount=[arrayPluSpecialSort count];
    for (NSDictionary *itemPluSpecialSort in arrayPluSpecialSort) {
        pluSpecialSortIndex++;
        PluSpecialSort *pluSpecialSort = [NSEntityDescription insertNewObjectForEntityForName:@"PluSpecialSort" inManagedObjectContext:MOC];
        [pluSpecialSort setPsSortCode:dictObject(itemPluSpecialSort, @"psSort")];               //烧法类别代码
        [pluSpecialSort setPsDescripts:dictObject(itemPluSpecialSort,@"psDescripts")];          //烧法类别描述
        [pluSpecialSort setPsRemarks:@""];                                                      //烧法类别备注
        [pluSpecialSort setPsPluSortCode:@""];                                                  //小类代码
        
        self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在下载烧法类别[code=%@,name=%@]下的明细信息...",pluSpecialSortIndex,pluSpecialSortCount,pluSpecialSort.psSortCode,JsonFiled(pluSpecialSort.psDescripts)];
        [self notifyMessage];
        
        NSString *urlPluSpecialCode = [NSString stringWithFormat:@"%@/update/PluSpecialCode/%@",BaseURL(baseUrl),pluSpecialSort.psSortCode];
        NSArray *arrayPluSpecialCode = [XRmenuHelper getDataFromInternet:urlPluSpecialCode Error:outError];//获得Json字符串数组
        int pluSpecialCodeIndex=0;
        int pluSpecialCodeCount=[arrayPluSpecialCode count];
        for (NSDictionary *itemPluSpecialCode in arrayPluSpecialCode) {
            pluSpecialSortIndex++;
            PluSpecialCode *pluSpecialCode = [NSEntityDescription insertNewObjectForEntityForName:@"PluSpecialCode" inManagedObjectContext:MOC];
            [pluSpecialCode setPsCode:dictObject(itemPluSpecialCode,@"psCode")];                    //烧法代码
            [pluSpecialCode setPsDescripts:dictObject(itemPluSpecialCode, @"psDescripts")];         //烧法描述
            [pluSpecialCode setPsRemarks:dictObject(itemPluSpecialCode, @"psRemarks")];             //烧法备注
            [pluSpecialCode setPsSortCode:dictObject(itemPluSpecialCode, @"psSort")];               //烧法类别代码
            [pluSpecialSort addRsToPluSpecialCodeObject:pluSpecialCode];//建立关系
            
            self.firstMessage = [NSString stringWithFormat:@"(%d/%d)正在下载烧法明细信息...",pluSpecialCodeIndex,pluSpecialCodeCount];
            [self notifyMessage];
        }
    }
    
    if ([MOC save:outError]) {
        status = YES;
        DebugLog(@"%@", @"烧法信息 更新成功!");
        self.exceptionMessage=[NSString stringWithFormat:@"烧法信息 更新成功!"];
        [self notifyMessage];
    }else {
        DebugLog(@"烧法信息 更新出错:%@", [*outError localizedDescription]);
        self.exceptionMessage=[NSString stringWithFormat:@"烧法信息 更新出错：%@", [*outError localizedDescription]];
        [self notifyMessage];
    }
    
    DebugLog(@"%@", @"-------烧法信息 更新结束!-------");
    self.firstMessage = @"烧法信息更新完毕!";
    [self notifyMessage];
    return status;
}
//OEM图片下载
-(BOOL) XRmenuOEMPictureUpdate:(NSString *)baseUrl Error:(XRmenuError **)outError{
    self.exceptionMessage = @"开始下载OEM图片...";
    [self notifyMessage];
    DebugLog(@"%@",@"-------开始下载OEM图片...-------");
    
    NSString *localName = [NSString stringWithFormat:@"%@/oem.png",[XRmenuFileManage documentPath]];
    DebugLog(@"localName=%@", localName);
    [XRmenuFileManage fileDelete:localName];//先删除老的oem.png
    [XRmenuHelper downloadFile:[NSString stringWithFormat:@"%@/Content/PluImgs/oem.png",BaseURL(baseUrl)] LocalFolder:localName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:localName error:nil];
    if (fileAttributes != nil) {
        NSNumber *size = [fileAttributes objectForKey:NSFileSize];
        DebugLog(@"size=%d", [size intValue]);
        if ([size intValue] <= 10000) {
            [XRmenuFileManage fileDelete:localName];
        }
    }
    if(![XRmenuFileManage fileExistByPath:localName]){
        self.exceptionMessage = [NSString stringWithFormat:@"不存在OEM图片！"];
        [self notifyMessage];
    }
    else{
        self.exceptionMessage = [NSString stringWithFormat:@"OEM图片下载成功！"];
        [self notifyMessage];
    }
    
    self.firstMessage = [NSString stringWithFormat:@"OEM图片更新完成！"];
    [self notifyMessage];
    
    return YES;
}
//菜品大图片文件下载
-(BOOL) XRmenuFilesUpdate:(NSString *)baseUrl Error:(XRmenuError **)outError{
    self.exceptionMessage = @"开始更新菜品图片...";
    [self notifyMessage];
    DebugLog(@"%@",@"-------开始更新 菜品图片...-------");
    
    [self clearFiles];//删除所有图片文件
    [self clearGridImages];//删除所有缩略图片文件
    NSMutableArray *arrayPluPlus=[NSMutableArray new];
    arrayPluPlus=[XRmenuCoreData getAllPluPlu];//查询所有菜品对象
    int plupluIndex=0;
    int plupluCount=[arrayPluPlus count];
    for (PluPlu *itemPluPlu in arrayPluPlus) {
        plupluIndex++;
        //指向大图下载目录
        NSString *localName = [NSString stringWithFormat:@"%@/XRmenu/dishphoto/%@%@",[XRmenuFileManage documentPath],itemPluPlu.ppPluPluId,@".png"];
        NSString *finalFolder = [NSString stringWithFormat:@"%@/XRmenu/dishphoto",[XRmenuFileManage documentPath]];
        NSError *error = nil;
        BOOL isDir;
        BOOL temp = [[NSFileManager defaultManager] fileExistsAtPath:finalFolder isDirectory:&isDir];
        if (!temp) {
            if ([[NSFileManager defaultManager] createDirectoryAtPath:finalFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
                DebugLog(@"%@文件夹创建成功!",finalFolder);
            }else {
                DebugLog(@"%@文件夹创建失败:%@",finalFolder, [error userInfo]);
                return NO;
            }
        }
        [XRmenuHelper downloadFile:[NSString stringWithFormat:@"%@/Content/PluImgs/%@%@",BaseURL(baseUrl),itemPluPlu.ppPluPluId,@".png"] LocalFolder:localName];//下载大图
        
        //指向缩略图下载目录
        NSString *localNameGrid = [NSString stringWithFormat:@"%@/XRmenu/grid/%@%@",[XRmenuFileManage documentPath],itemPluPlu.ppPluPluId,@".png"];
        NSString *finalFolderGrid = [NSString stringWithFormat:@"%@/XRmenu/grid",[XRmenuFileManage documentPath]];
        BOOL isDir1;
        BOOL temp1 = [[NSFileManager defaultManager] fileExistsAtPath:finalFolderGrid isDirectory:&isDir1];
        if (!temp1) {
            if ([[NSFileManager defaultManager] createDirectoryAtPath:finalFolderGrid withIntermediateDirectories:YES attributes:nil error:&error]) {
                DebugLog(@"%@文件夹创建成功!",finalFolderGrid);
            }else {
                DebugLog(@"%@文件夹创建失败:%@",finalFolderGrid, [error userInfo]);
                return NO;
            }
        }
        [XRmenuHelper downloadFile:[NSString stringWithFormat:@"%@/Content/GridImgs/%@%@",BaseURL(baseUrl),itemPluPlu.ppPluPluId,@".png"] LocalFolder:localNameGrid];//下载缩略图
        
        //删除大图
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:localName error:nil];
        if (fileAttributes != nil) {
            NSNumber *size = [fileAttributes objectForKey:NSFileSize];
            DebugLog(@"size=%d", [size intValue]);
            if ([size intValue] <= 10000) {
                [XRmenuFileManage fileDelete:localName];
            }
        }   
        if(![XRmenuFileManage fileExistByPath:localName]){
            self.exceptionMessage = [NSString stringWithFormat:@"菜品大图片[code=%@,name=%@]下载出错!原因：图片未上传或网络传输错误。",itemPluPlu.ppCode,JsonFiled(itemPluPlu.ppNames)];
            [self notifyMessage];
        }
        //删除小的缩略图片
        NSDictionary *fileAttributes1 = [fileManager attributesOfItemAtPath:localNameGrid error:nil];
        if (fileAttributes1 != nil) {
            NSNumber *size = [fileAttributes1 objectForKey:NSFileSize];
            DebugLog(@"size=%d", [size intValue]);
            if ([size intValue] <= 10000) {
                [XRmenuFileManage fileDelete:localNameGrid];
            }
        }
        if(![XRmenuFileManage fileExistByPath:localNameGrid]){
            self.exceptionMessage = [NSString stringWithFormat:@"菜品缩略图片[code=%@,name=%@]下载出错!原因：图片未上传或网络传输错误。",itemPluPlu.ppCode,JsonFiled(itemPluPlu.ppNames)];
            [self notifyMessage];
        }
        
        DebugLog(@"下载文件路径:%@",localName);
        self.firstMessage = [NSString stringWithFormat:@"正在更新菜品图片数据:(%d/%d)imgName=%@.png",plupluIndex,plupluCount,itemPluPlu.ppPluPluId];
        [self notifyMessage];
    }
    return YES;
}

#pragma mark -
#pragma mark 框架性初始化方法
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	CGRect contentRect = CGRectMake(0, 0, 1024, 768);
	CGRect frameCG = [self.view bounds];
	UIFont *tFont = [UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial"] objectAtIndex:1] size:15.0];
	
	// 设置背景图片
	UIImageView *imgView = [[UIImageView alloc] initWithFrame:contentRect];
	[imgView setImage:[UIImage imageNamed:@"UpdateBg.png"]];		
	[self.view addSubview:imgView];		
	[imgView release];
	
	//创建更新Label
	UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(frameCG.origin.x + 245.0f, frameCG.origin.y + 621.0f, 860.0f, 55.0f)];
	[titleLabel setText:[NSString stringWithFormat:@"正在更新系统数据UDID=%@",APPSESSION.udid]];
	[titleLabel setBackgroundColor:[UIColor clearColor]];
	[titleLabel setOpaque:NO];
	[titleLabel setTextColor:colorx(12542240)];
	[titleLabel setHighlightedTextColor:[UIColor whiteColor]];
	[titleLabel setFont:tFont];
	[titleLabel setMinimumFontSize:13.0f];
	[titleLabel setAdjustsFontSizeToFitWidth:YES];
	[titleLabel setTextAlignment:UITextAlignmentLeft];
	[self.view addSubview:titleLabel];
	[titleLabel release];
	
	UIFont *tFont2 = [UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial"] objectAtIndex:1] size:15.0];
	UILabel *updateLabel = [[UILabel alloc] initWithFrame:CGRectMake(frameCG.origin.x + 255.0f, frameCG.origin.y + 693.0f, 500.0f, 20.0f)];
	[updateLabel setText:@"开始更新菜谱数据!"];
	[updateLabel setBackgroundColor:[UIColor clearColor]];
	[updateLabel setOpaque:NO];
	[updateLabel setTextColor:colorx(12542240)];
	[updateLabel setHighlightedTextColor:[UIColor whiteColor]];
	[updateLabel setFont:tFont2];
	[updateLabel setMinimumFontSize:8.0f];
	[updateLabel setAdjustsFontSizeToFitWidth:YES];
	[updateLabel setTextAlignment:UITextAlignmentLeft];
	self.tableUpdateLabel = updateLabel;
	[updateLabel release];
	[self.view addSubview:tableUpdateLabel];
    
    //exception textView
    UITextView *tmpV =  [[[UITextView alloc] initWithFrame:CGRectMake(frameCG.origin.x + 200.0f, frameCG.origin.y + 50.0f, 700.0f, 820.0f)] autorelease];
    tmpV.font=tFont2;
    tmpV.editable=NO;
	tmpV.backgroundColor = [UIColor clearColor];
	tmpV.text=@"开始更新菜谱数据...";
	tmpV.returnKeyType = UIReturnKeyDefault;
	tmpV.keyboardType = UIKeyboardTypeDefault;
	tmpV.scrollEnabled = YES;
	tmpV.autoresizingMask = UIViewAutoresizingFlexibleHeight;
	[tmpV setTag:kTagOfStartUpdateText];
	[self.view addSubview:tmpV];  
	
    //progressBar
	XRProgressBarView *tkBar = [[XRProgressBarView alloc] initWithStyle:TKProgressBarViewStyleLong];
	[tkBar setProgress:0.00f];
	[tkBar setCenter:CGPointMake(531.0f,673.0f)];
	self.progressbar = tkBar;
	[tkBar release];
	[self.view addSubview:progressbar];
	
	// 注册多线程下的刷新机制及启动多线程方法
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateProgress:) name:@"RefreshUI" object:nil];
	//[NSThread detachNewThreadSelector:@selector(startBackgroundJob) toTarget:self withObject:nil];
	[self performSelectorInBackground:@selector(startBackgroundJob) withObject:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ;
}
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshUI" object:nil];
	
	[tableUpdateLabel release];
    tableUpdateLabel = nil;
    [firstMessage release];
    firstMessage = nil;
    [exceptionMessage release];
    exceptionMessage = nil;
    [progressbar release];
    progressbar = nil;
    departmentId = nil;
	
    [super dealloc];
}
@end